// 路由签权，项目当中的路由能不能被访问的权限
import router from '@/router'

import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })

import useUserStore from './store/modules/user'
import pinia from './store'
import setting from './setting'

let userStore = useUserStore(pinia)

//全局的前置守卫
router.beforeEach(async (to, _from, next) => {
  document.title = `${setting.title} - ${to.meta.title}`
  // to 你将要访问那个路由
  // from  从那个路由过来
  // 路由放行的函数
  nprogress.start()
  let token = userStore.token
  let username = userStore.username

  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (error) {
          await userStore.logout()
          next({
            path: '/login',
            query: {
              redirect: to.path,
            },
          })
        }
      }
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.path,
        },
      })
    }
  }
})

//全局的后置守卫
router.afterEach((_to, _from) => {
  nprogress.done()
})

// 实现进度条功能 -- pnpm i nprogress
